import { Inject, Middleware, httpError } from "@midwayjs/core";
import { Context, NextFunction } from "@midwayjs/koa";
import { JwtService } from "@midwayjs/jwt";

@Middleware()
export class JwtMiddleware {
  @Inject()
  jwtService: JwtService;

  resolve() {
    return async (ctx: Context, next: NextFunction) => {
      const token = ctx.request.header["token"];
      // 判断下有没有校验信息
      if (!token) {
        throw new httpError.UnauthorizedError("未授权的非法访问");
      }
      await this.jwtService.verifySync(token.toString(), {
        complete: true,
      });
      await next();
    };
  }

  // 配置忽略认证校验的路由地址
  public match(ctx: Context): boolean {
    const ignore = ["/user/login"].includes(ctx.request.url);
    return !ignore;
  }
}
